package com.smart.primary.util.creat;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil {
	
	/*
	 * 字符串转码
	 */
    public static String encode(String str){
        try {
            return URLEncoder.encode(str,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }
    /*
     * 字符串解码
     */
    public static String decode(String str){
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }



    /*
     * 字符串转集合
     */
     public static List<String> strToList(String str,String sp){
    	List<String> list= new ArrayList<String>();
        if(StringUtils.isBlank(str) || sp == null){
            return list;
        }
        str=trim(str);
        String[] arr=str.split(sp);
        for (String string : arr) {
        	if(StringUtils.isNotBlank(string)){
        		list.add(string);
            }
		}
        return list;
    }
     public static List<String> strToList(String str){
    	return strToList(str,",");
    }
    /*
     * 添加逗号
     */
     public static String addComma(String...str){
		if(str==null){
			return "";
		}
		StringBuffer ss=new StringBuffer();
	 	for (String string : str) {
			if(StringUtils.isNotBlank(string)){
				ss.append(string+",");
			}
		}
	    return ss.length()>0?ss.insert(0,",").toString():"";
	}
     
    /*
     * 字符串去除前后指定字符
     */
    public static String trim(String str,String rep){
        if(StringUtils.isBlank(str)){
            return "";
        }
        str=str.trim();
        if(rep==null || rep.length()==0){
            return str;
        }
        String regex = "^"+rep+"*|"+rep+"*$";
        return str.replaceAll(regex, "").trim();
    }

    public static String trim(String str){
        return trim(str, ",");
    }
    

    /*
     * 判断字符串的编码
     */
    public static String getEncoding(String str) {
        String encode[] = new String[]{
                "UTF-8",
                "ISO-8859-1",
                "GB2312",
                "GBK",
                "GB18030",
                "Big5",
                "Unicode",
                "ASCII"
        };
        for (int i = 0; i < encode.length; i++) {
            try {
                if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {
                    return encode[i];
                }
            } catch (Exception ex) {
            }
        }
        return "";
    }

    /*
     * 获取字符在字符串中出现第N次的下标
     * @param string
     * @param comp
     * @param i
     * @return
     */
    public static int getStrInd(String string,String comp,int i){
        try {
        	//这里是获取"/"符号的位置
            Matcher slashMatcher = Pattern.compile(comp).matcher(string);
            int mIdx = 0;
            while(slashMatcher.find()) {
                mIdx++;
                if(mIdx == i){
                    break;
                }
            }       	
            return slashMatcher.start();
        }catch (Exception e){
            return -1;
        }
    }

    public static void main(String[] args) {
        int i=StringUtils.ordinalIndexOf("192.168.1.1","1",3);
        System.out.println(i);
    }

    /**
     *
     * @param str
     * @param i
     * @return
     */
    public static String subIndOf(String str,String indOf,int i){
       try {
           for (int j=0;j<Math.abs(i);j++){
               if(i>0){
                   str=str.substring(0,str.indexOf(indOf));
               }else{
                   str=str.substring(0,str.lastIndexOf(indOf));
               }
           }
       }catch (Exception e){
           System.out.println("下标越界");
       }
        return str;
    }


    //首字母转小写
    public static String toLowerOne(String s){
    	if(StringUtils.isBlank(s)){
    		return "";
    	}
    	s=trim(s);
        if(Character.isLowerCase(s.charAt(0))) {
            return s;
        }else {
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }
    //首字母转大写
    public static String toUpperOne(String s){
    	if(StringUtils.isBlank(s)){
    		return "";
    	}
    	s=trim(s);
        if(Character.isUpperCase(s.charAt(0))) {
            return s;
        }else {
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

    //  是否含有大写字母
    public static Boolean isUpperCase(String word){
    	if(StringUtils.isBlank(word)){
    		 return false;
    	}
        for(int i = 0; i < word.length(); i++){
            if (Character.isUpperCase(word.charAt(i))){
                return true;
            }
        }
        return false;
    }




    /**
     * Md5加密
     */
    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /*
     * 字符串中大写字母转小写  并在前面加指定字符
     */
    public static String addStr(String str,String cc) {
        if(StringUtils.isBlank(str)){
            return "";
        }
        StringBuffer sbf = new StringBuffer();
        char[] ch = str.toCharArray();
        for (char c : ch) {
            if (Character.isUpperCase(c)){
                sbf.append(cc+(char)(c+32));
            }else {
                sbf.append(c);
            }
        }
        return trim(sbf.toString(),cc);
    }
    public static String addStr(String str) {
    	return addStr(str,"_");
    }


    public static String removeLine(String str) {
        if(StringUtils.isBlank(str)){
            return "";
        }
        str=trim(str,"_");
        char[] ch = str.toCharArray();
        if(Character.isUpperCase(ch[0]) ){
            ch[0]=(char)(ch[0]+32);
        }
        for (int i=0 ;i<ch.length;i++) {
            if(ch[i]=='_'){
                if (i+1<ch.length && Character.isLowerCase(ch[i+1])){
                    ch[i+1]=(char)(ch[i+1]-32);
                }
            }
        }
        return String.valueOf(ch).replace("_","");
    }

    /*
     * 去除括号里的内容
     *  也可以str.replaceAll("\\(.+?\\)","")
     */

    public static String removeStr(String str) {
    	int i=str.lastIndexOf("(");
    	int j=str.indexOf(")",i);
    	if(i<j && i!=-1 && j!=-1){
    		str=str.substring(0,i)+str.substring(j+1);
    	}
    	int i1=str.lastIndexOf("(");
    	int j1=str.indexOf(")",i1);
    	if(i1<j1 && i1!=-1 && j1!=-1){
    		str=removeStr(str);
    	}
    	return str;
    }
    /*
     * 中英文混合的区分
     */

    public static void disStr(String s) {
        // 英文组合
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(s);
        while (m.find()) {
            System.out.println(m.group());           
        }
        // 非英文组合
        p = Pattern.compile("[^a-zA-Z]+");
        m = p.matcher(s);
        while (m.find()) {
            System.out.println(m.group());           
        }
    }
    
    public static List<String> subStr(String str){
    	String[] ss = str.split("");
    	List<String> map=new ArrayList<String>();
    	StringBuffer sb=new StringBuffer();
    	StringBuffer sb2=new StringBuffer();
    	for (String s : ss) {
			if(s.getBytes().length>1){
				sb.append(s);
				if(sb2.length()>0){
					map.add(sb2.toString());
					sb2.setLength(0);
				}
			}else{
				sb2.append(s);
				if(sb.length()>0){
					map.add(sb.toString());
					sb.setLength(0);
				}
			}			
		}
    	if(sb.length()>0){
			map.add(sb.toString());
		}
    	if(sb2.length()>0){
			map.add(sb2.toString());
		}
        return map;
    }
    
    /*
     * 获取指定字符出现的次数
     */
    public static int countChar(String str,char ch) {
        if(StringUtils.isBlank(str)){
            return 0;
        }
        // 将字符串转换为字符数组
        char[] chs = str.toCharArray();
        // 定义变量count存储字符串出现次数
        int count = 0;
        for(int i = 0;i < chs.length;i++) {
            if(chs[i] == ch) {
                count++;
            }
        }
        return count;
    }
    /*
     * 获取指定字符串出现的次数
     */
    public static int countStr(String string,String comp) {
         int mIdx = 0;
         if(string != null && comp != null){
        	 Matcher slashMatcher = Pattern.compile(comp).matcher(string);
             while(slashMatcher.find()) {
                 mIdx++;
             } 
         }
         return mIdx;
    }
    
    //英译汉
    public static String getChinese(String english) {
		if(StringUtils.isBlank(english)){
			return "";
		}
		english=english.replace("_", " ");
        english=addStr(english," ");   
        List<String> list= strToList(english," ");
        String ret="";
        for (String str : list) {
            if (geDictionary().containsKey(str)) {
                ret+= geDictionary().get(str);
            }
        }
        return ret;
    }

    
    // 英译汉 词库
    public static Map<String, String> geDictionary() {
        Map<String, String> m = new HashMap<String, String>();
        m.put("dictionary", "字典");
        m.put("map", "地图");
        m.put("love", "爱");
        m.put("cat", "类别");
        m.put("dog", "狗");
        m.put("bird", "鸟");
        m.put("is", "是否");
        m.put("use", "可用");
        m.put("time", "时间");
        m.put("add", "添加");
        m.put("update", "更新");
        m.put("user", "用户");
        m.put("admin", "管理员");
        m.put("log", "日志");
        m.put("status", "状态");
        m.put("position", "位置");
        m.put("media", "媒介");
        m.put("type", "类型");
        m.put("ad", "广告");
        m.put("name", "名字");
        m.put("img", "图片");
        m.put("start", "开始");
        m.put("end", "结束");
        m.put("click", "点击");
        m.put("count", "次数");
        m.put("enabled", "是否可行");
        m.put("info", "信息");
        m.put("address", "地址");
        m.put("sex", "性别");
        m.put("phone", "手机");
        m.put("password", "密码");
        m.put("pwd", "密码");
        m.put("birthday", "生日");
        m.put("money", "资金");
        m.put("frozen", "冻结");
        m.put("rank", "等级");
        m.put("points", "积分");
        m.put("pay", "支付");
        m.put("last", "最后");
        m.put("validated", "验证");
        m.put("role", "角色名");
        m.put("permissions", "权限");
        m.put("home", "家");
        m.put("account", "账户");
        m.put("width", "宽度");
        m.put("height", "高度");
        m.put("desc", "描述");
        m.put("agency", "代理商");
        m.put("bank", "银行");
        m.put("price", "价格");
        m.put("order", "订单");
        m.put("goods", "商品");
        m.put("sort", "排序");
        m.put("val", "值");
        m.put("value", "值");
        m.put("title", "标题");
        m.put("number", "数量");
        m.put("num", "数量");
        m.put("dispose", "处理");
        m.put("unit", "单位");
        m.put("show", "显示");
        m.put("nav", "导航栏");
        m.put("in", "在");
        m.put("grade", "分级");
        m.put("comment", "评论");
        m.put("content", "内容");
        m.put("max", "最大");
        m.put("min", "最小");
        m.put("send", "发送");
        m.put("coupon", "优惠券");
        m.put("sn", "序号");
        m.put("suppliers", "供应商");
        m.put("parent", "上级");
        m.put("msg", "消息");
        m.put("sell", "销售");
        m.put("date", "日期");
        m.put("real", "现实");
        m.put("attr", "属性");
        m.put("step", "步骤");
        m.put("market", "市场");
        m.put("consignee", "收件人");
        m.put("insure", "保证");
        m.put("shipping", "物流");
        m.put("color", "颜色");
        m.put("code", "代码");
        m.put("action", "行动");
        m.put("login", "登陆");
        m.put("style", "风格");
        m.put("valid", "有效期");
        m.put("front", "正面");
        m.put("verso", "背面");
        return m;
    }
}
